package com.cliang.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 注解实现用户过滤@WebFilter将一个实现了javax.servlet.Filte接口的类定义为过滤器组件
 *
 属性filterName声明过滤器的名称,可选
 *
 属性urlPatterns指定要过滤 的URL模式,也可使用属性value来声明.(指定要过滤的URL模式是必选属性)
 */
@WebFilter(filterName = "loginFilter",urlPatterns = "/blog/private/*")
public class LoginFilter implements Filter{
    private FilterConfig config=null;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        config=filterConfig;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding("UTF-8");
        servletResponse.setCharacterEncoding("UTF-8");
        servletResponse.setContentType("text/html;charset=UTF-8");

        HttpSession session=((HttpServletRequest)servletRequest).getSession();
        if(session.getAttribute("loginUser")==null){
            PrintWriter printWriter=servletResponse.getWriter();
//            printWriter.print("<script language=javascript>alert('请先登录！');window.location.href='/blog/login/login.html'</script>");
            printWriter.print("<link rel='stylesheet' href='/blog/common/layui/css/layui.css'>");
            printWriter.print("<script src='/blog/common/layui/layui.js'></script>");
            printWriter.print("<script language=javascript>layui.config({base:'/blog/js/'}).use(['layer'], function () {" +
                    " layer.confirm('请先登录！',{btn:'确定'}, function(){window.location.href='/blog/login/login.html'});});</script>");
        }else {
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }
}
